import webapp2
import json
from google.appengine.ext import db
from location import Location
from location import LocationService
from category import Category

class Place(db.Model):
  name = db.StringProperty()
  googlePlaceId = db.StringProperty()
  location = db.GeoPtProperty()
  category = db.ReferenceProperty(Category)

class PlacesRequestHandler(webapp2.RequestHandler):
  def get(self):
    params = self.request.params

    if params.has_key('lat') and params.has_key('long'):
      location = Location()
      location.lat = params['lat']
      location.long = params['long']

    if params.has_key('radius'):
      radius = params['radius']
    else:
      radius = 500

    if params.has_key('category'):
      category = params['category']

    if location:
      locationService = LocationService()
      googlePlaces = locationService.getNearBy(location, radius)
      translated = self.__translate(googlePlaces)
      self.__showJson(translated, self.response)

  def __translate(self, googlePlaces):
    """
    gets the list of google places,
    retuns a list of places in the expected json format, with our DB ids
    """
    ret_places = []
    for place in googlePlaces:
      ret_p = {
          'id': place['id'],
          'name': place['name'],
          #'address': self.get_address(place['reference']),
          'lat': place['geometry']['location']['lat'],
          'long': place['geometry']['location']['lng'],
        }
      
      ret_places.append(ret_p)
      # "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
      # "reference" : "CmRcAAAA_M8ocEZonopwZCSR_81GMKOVGvUQ2KQ6OtaHbYeejKkKjwfXSVQjBs-sHdXZjTTcjDFB8v7wRe4VBr7aj_UkZdcRRQXHg9UZs9xoU9hxTaL6Pg2JxH6tfeNP7IRwtTswEhDHqVQ8iOnzIxMVk4_LR1YvGhShKlz1RxiNMMs12uyP5d_ybJKqRQ",
    return json.dumps(ret_places)

  def __showJson(self, places, response):
    response.headers['Content-Type'] = 'application/json'
    response.out.write(json.dumps(places))

